package judesart.app.client.ui.pub.gallery;

import java.util.ArrayList;
import java.util.List;

import judesart.app.client.controller.GalleryController;
import judesart.app.client.controller.GalleryControllerAsync;
import judesart.app.client.facebook.FbUtil;
import judesart.app.client.ui.pub.layout.PublicMainLayout;
import judesart.app.domain.Gallery;
import judesart.app.domain.Room;

import com.allen_sauer.gwt.log.client.Log;
import com.extjs.gxt.ui.client.data.BaseListLoader;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelReader;
import com.extjs.gxt.ui.client.data.ListLoadResult;
import com.extjs.gxt.ui.client.data.ListLoader;
import com.extjs.gxt.ui.client.data.MemoryProxy;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.Composite;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.ListView;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class GalleryPanel extends Composite {
    GalleryControllerAsync galleryController = GalleryController.Util.getInstance();

    private final LayoutContainer mainPanel;
    private final Html htmlTitle;
    private final Html htmlDescription;
    private Gallery gallery;
    private final ListView<BeanModel> listViewRooms;
    private final List<Room> rooms = new ArrayList<Room>();
    private final ListLoader<ListLoadResult<Room>> loader;

    private final Html htmlFbLike;

    public GalleryPanel() {
        mainPanel = new LayoutContainer();
        mainPanel.setWidth(900);
        mainPanel.setStyleAttribute("min-height", "600px");
        mainPanel.setBorders(false);
        mainPanel.setId("id-jaw-GalleryPanel");

        MemoryProxy<List<Room>> proxy = new MemoryProxy<List<Room>>(rooms);
        loader = new BaseListLoader<ListLoadResult<Room>>(proxy, new BeanModelReader());
        ListStore<BeanModel> store = new ListStore<BeanModel>(loader);
        loader.load();

        LayoutContainer galleryInfoPanel = new LayoutContainer();

        htmlTitle = new Html();
        htmlTitle.setTagName("h1");
        htmlTitle.setId("id-jaw-GalleryPanel-title");
        galleryInfoPanel.add(htmlTitle);

        htmlDescription = new Html();
        htmlDescription.setTagName("div");
        htmlDescription.setId("id-jaw-GalleryPanel-description");
        galleryInfoPanel.add(htmlDescription);

        htmlFbLike = new Html();
        htmlFbLike.setId("id-jaw-GalleryPanel-fbLike");
        htmlFbLike.setTagName("div");
        galleryInfoPanel.add(htmlFbLike);

        galleryInfoPanel.setWidth(300);
        galleryInfoPanel.setBorders(false);
        galleryInfoPanel.setId("id-jaw-GalleryPanel-info");
        galleryInfoPanel.setStyleAttribute("float", "left");
        mainPanel.add(galleryInfoPanel);

        listViewRooms = new ListView<BeanModel>(store) {
            @Override
            protected BeanModel prepareData(BeanModel model) {
                Room g = model.getBean();
                if (g.getArtworks() != null && g.getArtworks().size() > 0) {
                    model.set("mainImageId",
                            g.getArtworks().get(0).getMainImageId());
                    model.set("artworksCount", g.getArtworks().size());
                }
                return model;
            }
        };
        listViewRooms.setLoadingText("loading...");
        listViewRooms.setBorders(false);
        listViewRooms.setWidth(580);
        listViewRooms.setStyleAttribute("float", "right");
        listViewRooms.setStyleAttribute("overflow-y", "hidden");
        listViewRooms.setHeight("100%");
        listViewRooms.setStyleAttribute("min-height", "600px");
        listViewRooms.setTemplate(getTemplate());
        listViewRooms.setItemSelector("div.thumb-wrap");
        listViewRooms.getSelectionModel().addListener(Events.SelectionChange,
                new Listener<SelectionChangedEvent<BeanModel>>() {
                    public void handleEvent(SelectionChangedEvent<BeanModel> be) {
                        onSelectionChanged(be);
                    }
                });
        listViewRooms.setId("id-jaw-GalleryPanel-rooms");
        mainPanel.add(listViewRooms);

        initComponent(mainPanel);
    }

    public void openGallery(Long galleryId) {
        galleryController.getGallery(galleryId, new AsyncCallback<Gallery>() {

            @Override
            public void onSuccess(Gallery result) {
                Log.debug(" < getGallery [" + result.getId() + "]");
                setGallery(result);
                PublicMainLayout.getInstance().loading(false);
            }

            @Override
            public void onFailure(Throwable caught) {
                Log.error("Unable to open gallery", caught);
                PublicMainLayout.getInstance().loading(false);
            }
        });
    }

    private void setGallery(Gallery gallery) {
        this.gallery = gallery;
        rooms.clear();
        if (this.gallery.getRooms() != null) {
            rooms.addAll(this.gallery.getRooms());
        }
        htmlTitle.setHtml(gallery.getTitle());
        htmlDescription.setHtml(gallery.getDescription());
        String title = gallery.getTitle();
        String image = "http://www.judithshaylor.com/image/"
                + gallery.getRooms().get(0).getArtworks().get(0).getMainImageId()
                + "_75x75_crop";
        String url = "http://www.judithshaylor.com/rd/gallery/" + gallery.getId();
        String description = gallery.getDescription();
        FbUtil.setOgMeta(getElement(), title, image, url, description);
        htmlFbLike.setHtml(FbUtil.like("gallery/" + gallery.getId()));
        loader.load();
        PublicMainLayout.getInstance().layout(true);
        FbUtil.parseFBML("id-jaw-GalleryPanel-fbLike");
    }

    private native String getTemplate() /*-{
        return ['<tpl for=".">', 
        '<div style="float:left;margin:2em 0 2em 2em; padding:2px;width:240px; height: 240px;" class="thumb-wrap" id="{mainImageId}">', 
        '<div style="width: 100%;" class="thumb"><img src="/image/{mainImageId}_240x240"></div>', 
        '<div style="width: 100%;" class="thumb-legend">{name}<span>({artworksCount} artworks)</span></div>',
        '</div>',
        '</tpl>', 
        '<div class="x-clear"></div>'].join("");
    }-*/;

    private void onSelectionChanged(SelectionChangedEvent<BeanModel> be) {
        Object source = be.getSource();
        Log.debug("source [" + source + "]");
        if (be.getSelection().size() == 0) {
            return;
        }
        final BeanModel model = be.getSelection().get(0);
        Room room = model.getBean();
        History.newItem("room/" + room.getKey());
    }
}
